package com.bridgeintelligent.tag.customer.provider;

import com.alibaba.fastjson.JSONObject;
import com.bridgeintelligent.tag.customer.entity.CustomersPage;
import com.bridgeintelligent.tag.customer.pojo.CCISQueryResult;
import com.bridgeintelligent.tag.customer.service.ICustomerApprovalService;
import com.bridgeintelligent.tag.user.mgmt.exception.UserException;
import com.bridgeintelligent.tag.utils.DateHelper;
import com.bridgeintelligent.tag.utils.IdWorker;
import com.bridgeintelligent.tag.webserver.dim.query.api.CustQuerySetRsp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(tags = "客群对外服务接口")
@AllArgsConstructor
@RestController
@RequestMapping("/api/provider")
@Slf4j
public class ProviderController {


    private IProviderService providerService;

    private ICustomerApprovalService customerApprovalService;


    /**
     * 客群筛选条件转SQL
     * @return
     */
    @ApiOperation("客群筛选条件转SQL")
    @PostMapping("/sql")
    public ResVO sql(@RequestBody String jsonStr) {
        log.info("客群筛选条件转SQL报文:{}",jsonStr);
        ResVO resVO = null;
        ReqVO reqVO = null;
        try {
            reqVO = JSONObject.parseObject(jsonStr, ReqVO.class);
            ReqBody reqBody = reqVO.getBody();
            if (!providerService.checkDataById(reqBody.getCustomerId())){
                resVO = getResult("1","该客群不可用！",null,"",null,null, reqVO);
            }else {
                String sqlStr = providerService.findFilterGroup(reqBody.getCustomerId(),"");
                resVO = getResult("0","查询成功",null,sqlStr,null,null,reqVO);
            }
        } catch (UserException e) {
            log.info("客群筛选条件转SQL出现异常--：{}",e);
            resVO = getResult("1","客群筛选条件转SQL异常",null,"",null,null, reqVO);
        }
        return resVO;
    }

    /**
     * 客群筛选条件转SQL---跟上述sql接口完全一样，只是在service里
     * 拼接了不同的表，但在三方平台暴露的交易码不一样
     * @return
     */
    @ApiOperation("客群筛选条件转SQL1")
    @PostMapping("/sql1")
    public ResVO sql1(@RequestBody String jsonStr) {
        log.info("客群筛选条件转SQL1报文:{}",jsonStr);
        ResVO resVO = null;
        ReqVO reqVO = null;
        try {
            reqVO = JSONObject.parseObject(jsonStr, ReqVO.class);
            ReqBody reqBody = reqVO.getBody();
            if (!providerService.checkDataById(reqBody.getCustomerId())){
                resVO = getResult("1","该客群不可用！",null,"",null,null, reqVO);
            }else{
                String sqlStr = providerService.findFilterGroup(reqBody.getCustomerId(),"1");
                resVO = getResult("0","查询成功",null,sqlStr,null,null,reqVO);
            }
        } catch (UserException e) {
            log.info("客群筛选条件转SQL出现异常--：{}",e);
            resVO = getResult("1","客群筛选条件转SQL异常",null,"",null,null, reqVO);
        }
        return resVO;
    }

    /**
     * 客群列表查询
     * @return
     */
    @ApiOperation("客群列表查询服务")
    @PostMapping("/info")
    public ResVO info(@RequestBody String jsonStr) {
        log.info("客群列表查询报文:{}",jsonStr);
        ResVO resVO = null;
        ReqVO reqVO = null;
        try {
            reqVO = JSONObject.parseObject(jsonStr, ReqVO.class);
            ReqBody reqBody = reqVO.getBody();
            int pageNumber = reqBody.getPageNumber() == null ? 1 : reqBody.getPageNumber();
            int pageSize = reqBody.getPageSize() == null ? 10 : reqBody.getPageSize();
            CustomersPage<CustomerInfoVO> page =  providerService.findPage(reqBody.getUserId(),reqBody.getCustomerName(),reqBody.getUptTimeStart(),reqBody.getUptTimeEnd(),pageNumber,pageSize);
            resVO = getResult("0","查询成功",page,"",null, null,reqVO);
        } catch (UserException e) {
            log.info("客群列表对外服务查询出现异常--：{}",e);
            resVO = getResult("1","客群列表查询异常",null,"",null, null,reqVO);
        }
        return resVO;
    }

    /**
     * 标签目录列表
     * @return
     */
    @ApiOperation("标签目录列表")
    @PostMapping("/catalog")
    public ResVO catalog(@RequestBody String jsonStr) {
        log.info("标签目录列表报文:{}",jsonStr);
        ResVO resVO = null;
        ReqVO reqVO = null;
        try {
            reqVO = JSONObject.parseObject(jsonStr, ReqVO.class);
            ReqBody reqBody = reqVO.getBody();
            List<CatalogInfoVO> catalogs = providerService.findCatalogList();
            resVO = getResult("0","查询成功",null,"",catalogs,null,reqVO);
        } catch (UserException e) {
            log.info("标签目录列表出现异常--：{}",e);
            resVO = getResult("1","标签目录列表异常",null,"",null, null,reqVO);
        }
        return resVO;
    }

    /**
     * 根据目录ID查询标签列表
     * @return
     */
    @ApiOperation("根据目录ID查询标签列表")
    @PostMapping("/dimInfo")
    public ResVO dimInfo(@RequestBody String jsonStr) {
        log.info("根据目录ID查询标签列表报文:{}",jsonStr);
        ResVO resVO = null;
        ReqVO reqVO = null;
        try {
            reqVO = JSONObject.parseObject(jsonStr, ReqVO.class);
            ReqBody reqBody = reqVO.getBody();
            int pageNumber = reqBody.getPageNumber() == null ? 1 : reqBody.getPageNumber();
            int pageSize = reqBody.getPageSize() == null ? 10 : reqBody.getPageSize();
            CustomersPage<DimInfoVO> page =  providerService.getDimInfo(reqBody.getCatalogId(),pageNumber,pageSize);
            resVO = getResult("0","查询成功",null,"",null, page,reqVO);
        } catch (UserException e) {
            log.info("客群列表对外服务查询出现异常--：{}",e);
            resVO = getResult("1","客群列表查询异常",null,"",null,null, reqVO);
        }
        return resVO;
    }

    /**
     * 根据目录ID查询标签列表
     * @return
     */
    @ApiOperation("根据客群ID输出指定字段")
    @PostMapping("/custQuery")
    public ResVO custQuery(@RequestBody String jsonStr) {
        log.info("根据客群ID输出指定字段报文:{}",jsonStr);
        ResVO resVO = null;
        ReqVO reqVO = null;
        try {
            reqVO = JSONObject.parseObject(jsonStr, ReqVO.class);
            ReqBody reqBody = reqVO.getBody();
            if (!providerService.checkDataById(reqBody.getCustomerId())){
                resVO = getCustQueryResult(1,"该客群不可用！",null, reqVO);
            }else{
                CustQuerySetRsp custQuerySetRsp =  providerService.custQuery(reqBody.getCustomerId(),reqBody.getPageNumber(),reqBody.getPageSize());
                resVO = getCustQueryResult(custQuerySetRsp.getCode(), custQuerySetRsp.getMsg(), custQuerySetRsp,reqVO);
            }
        } catch (UserException e) {
            log.info("根据客群ID输出指定字段出现异常--：{}",e);
            resVO = getCustQueryResult(1,"根据客群ID输出指定字段异常",null, reqVO);
        }
        return resVO;
    }

    private ResVO getCustQueryResult(int code, String msg, CustQuerySetRsp resp,ReqVO reqVO){
        ResVO resVO = new ResVO();
        HeadVO head = new HeadVO()
                .setSrcChnlNo(reqVO.getHead().getSrcChnlNo())
                .setDstChnlNo(reqVO.getHead().getDstChnlNo())
                .setAnsTranCode(reqVO.getHead().getAnsTranCode())
                .setAnsTranDate(DateHelper.currentDateTime(DateHelper.PATTERN_DATE_8))
                .setTlrJourNo(IdWorker.nextId())
                .setRespCode(code+"")
                .setRespMsg(msg);
        resVO.setHead(head);
        if (code == 0){
            CustQueryResult result = new CustQueryResult()
                    .setContent(resp.getData().getContent())
                    .setPage(resp.getData().getPage())
                    .setSize(resp.getData().getSize())
                    .setTotalElements(resp.getData().getTotalElements())
                    .setTotalPages(resp.getData().getTotalPages());
            ResBody body = new ResBody().setResult(result);
            resVO.setBody(body);
        }
        return resVO;
    }


    private ResVO getResult(String code, String msg, CustomersPage<CustomerInfoVO> page, String sqlStr, List<CatalogInfoVO> catalogs, CustomersPage<DimInfoVO> pageDim,ReqVO reqVO){
        ResVO resVO = new ResVO();
        HeadVO head = new HeadVO()
                .setSrcChnlNo(reqVO.getHead().getSrcChnlNo())
                .setDstChnlNo(reqVO.getHead().getDstChnlNo())
                .setAnsTranCode(reqVO.getHead().getAnsTranCode())
                .setAnsTranDate(DateHelper.currentDateTime(DateHelper.PATTERN_DATE_8))
                .setTlrJourNo(IdWorker.nextId())
                .setRespCode(code)
                .setRespMsg(msg);
        resVO.setHead(head);
        if ("0".equals(code)){
            ResBody body = new ResBody().setPage(page).setSqlStr(sqlStr).setCatalogs(catalogs).setPageDim(pageDim);
            resVO.setBody(body);
        }

        return resVO;
    }

    /**
     * 员工自助系统审批结果通知
     * @return
     */
    @ApiOperation("员工自助系统审批结果通知")
    @PostMapping("/ccisMessage")
    public CCISQueryResult ccisMessage(@RequestBody String message) {
        try {
            customerApprovalService.handleCCISMessage(message);
            return CCISQueryResult.ok();
        } catch (Exception e) {
            log.info("员工自助系统审批结果通知处理异常--：{}",e);
            return CCISQueryResult.error("审批结果消息处理异常:"+e.getMessage());
        }
    }

}